import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Item {
    id: root
    
    // 标题
    Text {
        id: title
        text: "📏 身高成长记录"
        font.pixelSize: 28
        font.bold: true
        color: "#2c3e50"
        anchors.top: parent.top
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: 20
    }
    
    // 主内容区域
    Item {
        anchors.top: title.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 20
        
        // 折线图（占满整个区域）
        Rectangle {
            id: chartArea
            anchors.fill: parent
            color: "white"
            border.color: "#dfe6e9"
            border.width: 2
            radius: 10
            
            // 图表标题
            Text {
                id: chartTitle
                text: "身高成长曲线"
                font.pixelSize: 20
                font.bold: true
                color: "#34495e"
                anchors.top: parent.top
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.topMargin: 15
            }
            
            // Canvas绘制折线图
            Canvas {
                id: chartCanvas
                anchors.fill: parent
                anchors.leftMargin: 80  // 左边距增大，为Y轴标签留空间
                anchors.topMargin: 70
                anchors.bottomMargin: 60  // 减小底部边距，为X轴标签留空间
                anchors.rightMargin: 100
                
                property var dataPoints: []  // [{x, y, date, height, index}]
                
                Component.onCompleted: {
                    requestPaint();  // 初始化时绘制
                }
                
                onPaint: {
                    var ctx = getContext("2d");
                    ctx.clearRect(0, 0, width, height);
                    
                    if (heightRecordModel.count === 0) {
                        ctx.fillStyle = "#95a5a6";
                        ctx.font = "16px Arial";
                        ctx.textAlign = "center";
                        ctx.fillText("暂无数据，请添加身高记录", width / 2, height / 2);
                        return;
                    }
                    
                    // 从模型获取数据
                    var chartData = heightRecordModel.getChartData();
                    if (chartData.length === 0) return;
                    
                    // 计算高度范围（使用实际数据值）
                    var minHeight = 999999;
                    var maxHeight = 0;
                    
                    for (var i = 0; i < chartData.length; i++) {
                        // 确保正确获取height值
                        var item = chartData[i];
                        var h = item.height;
                        
                        // 如果是字符串，转换为数字
                        if (typeof h === "string") {
                            h = parseFloat(h);
                        }
                        
                        // 确保是数字
                        if (!isNaN(h) && h > 0) {
                            minHeight = Math.min(minHeight, h);
                            maxHeight = Math.max(maxHeight, h);
                        }
                    }
                    
                    // 如果数据无效，退出
                    if (minHeight === 999999 || maxHeight === 0) {
                        return;
                    }
                    
                    // 保存原始数据范围（用于显示Y轴刻度和计算数据点）
                    var originalMinHeight = minHeight;
                    var originalMaxHeight = maxHeight;
                    var originalRange = originalMaxHeight - originalMinHeight;
                    
                    if (originalRange < 0.1) {
                        // 如果范围太小，至少显示5cm的范围
                        originalMinHeight = Math.max(0, originalMinHeight - 2.5);
                        originalMaxHeight = originalMaxHeight + 2.5;
                        originalRange = originalMaxHeight - originalMinHeight;
                    }
                    
                    // 增加Y轴范围以便更好地显示（padding让图表更好看，数据点不贴边）
                    var heightRange = maxHeight - minHeight;
                    var yPadding = heightRange > 0 ? Math.max(heightRange * 0.1, 2) : 5;  // 至少2cm padding
                    var displayMinHeight = minHeight - yPadding;
                    var displayMaxHeight = maxHeight + yPadding;
                    var displayRange = displayMaxHeight - displayMinHeight;
                    
                    // 绘制网格线和Y轴刻度（使用原始数据范围显示绝对高度）
                    ctx.strokeStyle = "#ecf0f1";
                    ctx.lineWidth = 1;
                    ctx.fillStyle = "#7f8c8d";
                    ctx.font = "14px Arial";
                    ctx.textAlign = "right";
                    
                    // 计算合理的刻度间隔和范围
                    // 让刻度值更美观（整数或0.5的倍数），并且范围比数据范围大一些
                    var gridLines = 5;
                    var tickInterval = originalRange / gridLines;
                    
                    // 计算合理的刻度间隔（向上取整到0.5或1的倍数）
                    var niceInterval = 1.0;
                    if (tickInterval > 10) {
                        niceInterval = 5.0;
                    } else if (tickInterval > 5) {
                        niceInterval = 2.0;
                    } else if (tickInterval > 2) {
                        niceInterval = 1.0;
                    } else if (tickInterval > 1) {
                        niceInterval = 0.5;
                    } else {
                        niceInterval = 0.5;
                    }
                    
                    // 计算刻度范围（向下取整最小值，向上取整最大值）
                    // 增加一些padding，让数据点不贴边
                    var paddingTicks = 1;  // 上下各增加1个刻度间隔
                    var tickMin = Math.floor(originalMinHeight / niceInterval) * niceInterval - paddingTicks * niceInterval;
                    var tickMax = Math.ceil(originalMaxHeight / niceInterval) * niceInterval + paddingTicks * niceInterval;
                    var tickRange = tickMax - tickMin;
                    var actualGridLines = Math.round(tickRange / niceInterval);
                    
                    // 绘制Y轴刻度
                    for (var g = 0; g <= actualGridLines; g++) {
                        // 计算Y轴位置（从底部到顶部）
                        var yPos = height - (g / actualGridLines) * height;
                        
                        // 计算对应的绝对高度值（使用美观的刻度值）
                        var heightValue = tickMin + (g / actualGridLines) * tickRange;
                        
                        // 网格线（从Y轴标签右侧开始）
                        ctx.beginPath();
                        ctx.moveTo(50, yPos);
                        ctx.lineTo(width, yPos);
                        ctx.stroke();
                        
                        // Y轴标签 - 显示绝对高度
                        var labelText = heightValue.toFixed(heightValue % 1 === 0 ? 0 : 1) + " cm";
                        var textX = 45;  // X坐标，在网格线左侧
                        var textY = yPos + 4;  // Y坐标，微调位置让文本居中对齐网格线
                        ctx.fillText(labelText, textX, textY);
                    }
                    
                    // 计算数据点坐标（使用与Y轴刻度相同的范围，确保对齐）
                    dataPoints = [];
                    var chartLeftMargin = 50;  // 图表左边距（网格线起始位置）
                    var chartRightMargin = 20;  // 图表右边距
                    var chartWidth = width - chartLeftMargin - chartRightMargin;
                    
                    // 计算日期范围（用于按实际时间间隔分配X轴位置）
                    var minDate = null;
                    var maxDate = null;
                    var dateValues = [];  // 存储每个日期的时间戳（毫秒）
                    
                    for (var d = 0; d < chartData.length; d++) {
                        var dateStr = chartData[d].date;
                        var dateObj = new Date(dateStr);
                        if (isNaN(dateObj.getTime())) {
                            // 如果日期无效，尝试其他格式
                            dateObj = new Date(dateStr.replace(/-/g, '/'));
                        }
                        var timestamp = dateObj.getTime();
                        dateValues.push(timestamp);
                        
                        if (minDate === null || timestamp < minDate) {
                            minDate = timestamp;
                        }
                        if (maxDate === null || timestamp > maxDate) {
                            maxDate = timestamp;
                        }
                    }
                    
                    var dateRange = maxDate - minDate;
                    if (dateRange === 0) dateRange = 1;  // 避免除零
                    
                    for (var j = 0; j < chartData.length; j++) {
                        // 根据实际日期间隔计算X轴位置
                        var dateTimestamp = dateValues[j];
                        var normalizedDate = (dateTimestamp - minDate) / dateRange;  // 0到1之间
                        var xPos = chartLeftMargin + normalizedDate * chartWidth;
                        
                        // 使用刻度范围计算归一化高度（0到1之间）
                        var dataHeight = parseFloat(chartData[j].height);
                        var normalizedHeight = (dataHeight - tickMin) / tickRange;
                        
                        // 映射到Canvas的Y坐标
                        // Canvas坐标：y=0在顶部，y=height在底部
                        // 数据点：height值越大，y坐标越小（在顶部）
                        var yPos = height - normalizedHeight * height;
                        
                        dataPoints.push({
                            x: xPos,
                            y: yPos,
                            date: chartData[j].date,
                            height: chartData[j].height,
                            index: j
                        });
                    }
                    
                    // 绘制连接线
                    if (dataPoints.length > 1) {
                        ctx.strokeStyle = "#3498db";
                        ctx.lineWidth = 3;
                        ctx.beginPath();
                        ctx.moveTo(dataPoints[0].x, dataPoints[0].y);
                        for (var k = 1; k < dataPoints.length; k++) {
                            ctx.lineTo(dataPoints[k].x, dataPoints[k].y);
                        }
                        ctx.stroke();
                    }
                    
                    // 绘制数据点
                    for (var m = 0; m < dataPoints.length; m++) {
                        var point = dataPoints[m];
                        
                        // 外圈
                        ctx.fillStyle = "#3498db";
                        ctx.beginPath();
                        ctx.arc(point.x, point.y, 6, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 内圈
                        ctx.fillStyle = "white";
                        ctx.beginPath();
                        ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
                        ctx.fill();
                    }
                    
                    // 绘制X轴月份刻度（智能间隔）
                    ctx.strokeStyle = "#e0e0e0";
                    ctx.lineWidth = 1;
                    
                    // 计算起始和结束月份
                    var startDate = new Date(minDate);
                    var endDate = new Date(maxDate);
                    
                    // 计算时间跨度（月数）
                    var totalMonths = (endDate.getFullYear() - startDate.getFullYear()) * 12 + 
                                     (endDate.getMonth() - startDate.getMonth());
                    
                    // 根据时间跨度决定月份显示间隔
                    var monthInterval = 1;
                    if (totalMonths > 36) {
                        monthInterval = 6;  // 超过3年，每6个月显示
                    } else if (totalMonths > 18) {
                        monthInterval = 3;  // 1.5-3年，每3个月显示
                    } else if (totalMonths > 12) {
                        monthInterval = 2;  // 1-1.5年，每2个月显示
                    } else {
                        monthInterval = 1;  // 1年内，每月显示
                    }
                    
                    // 从起始日期的下个月1日开始
                    var currentMonth = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 1);
                    var monthCount = 0;
                    
                    while (currentMonth <= endDate) {
                        var monthTimestamp = currentMonth.getTime();
                        var normalizedMonth = (monthTimestamp - minDate) / dateRange;
                        var xPos = chartLeftMargin + normalizedMonth * chartWidth;
                        
                        // 只在间隔月份绘制网格线和显示标签
                        if (monthCount % monthInterval === 0) {
                            // 绘制垂直网格线
                            ctx.strokeStyle = "#e0e0e0";
                            ctx.lineWidth = 1;
                            ctx.beginPath();
                            ctx.moveTo(xPos, 0);
                            ctx.lineTo(xPos, height);
                            ctx.stroke();
                            
                            // 绘制月份标签（格式：2023-04）
                            ctx.fillStyle = "#7f8c8d";
                            ctx.font = "11px Arial";
                            ctx.textAlign = "center";
                            var monthLabel = currentMonth.getFullYear() + "-" + 
                                           String(currentMonth.getMonth() + 1).padStart(2, '0');
                            var labelY = height - 5;
                            ctx.fillText(monthLabel, xPos, labelY);
                        }
                        
                        // 移到下一个月
                        currentMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1);
                        monthCount++;
                    }
                    
                    // 绘制每个数据点的标签（日期 + 身高）- 交替上下显示避免重叠
                    ctx.font = "10px Arial";
                    ctx.textAlign = "center";
                    
                    for (var p = 0; p < dataPoints.length; p++) {
                        var point = dataPoints[p];
                        
                        // 交替显示在上方和下方
                        var isAbove = (p % 2 === 0);
                        var labelX = point.x;
                        var labelY;
                        
                        if (isAbove) {
                            // 显示在数据点上方
                            labelY = point.y - 20;
                        } else {
                            // 显示在数据点下方
                            labelY = point.y + 25;
                        }
                        
                        // 绘制半透明背景矩形（避免与网格线重叠）
                        var bgWidth = 80;
                        var bgHeight = 24;
                        var bgX = labelX - bgWidth / 2;
                        var bgY = labelY - 14;
                        
                        ctx.fillStyle = "rgba(255, 255, 255, 0.85)";
                        ctx.fillRect(bgX, bgY, bgWidth, bgHeight);
                        
                        // 绘制边框
                        ctx.strokeStyle = "#bdc3c7";
                        ctx.lineWidth = 1;
                        ctx.strokeRect(bgX, bgY, bgWidth, bgHeight);
                        
                        // 绘制文本
                        ctx.fillStyle = "#2c3e50";
                        
                        // 绘制日期
                        ctx.fillText(point.date, labelX, labelY);
                        
                        // 绘制身高（在日期下方）
                        ctx.fillStyle = "#3498db";
                        ctx.font = "bold 10px Arial";
                        ctx.fillText(point.height + " cm", labelX, labelY + 12);
                        
                        // 恢复字体
                        ctx.font = "10px Arial";
                    }
                }
                
                MouseArea {
                    anchors.fill: parent
                    
                    // PC双击删除
                    onDoubleClicked: function(mouse) {
                        // 检查是否点击了数据点
                        for (var i = 0; i < chartCanvas.dataPoints.length; i++) {
                            var point = chartCanvas.dataPoints[i];
                            var distance = Math.sqrt(Math.pow(mouse.x - point.x, 2) + Math.pow(mouse.y - point.y, 2));
                            
                            if (distance < 15) { // 点击容差
                                deleteDialog.recordIndex = point.index;
                                deleteDialog.recordDate = point.date;
                                deleteDialog.recordHeight = point.height;
                                deleteDialog.open();
                                return;
                            }
                        }
                    }
                    
                    // 移动端长按删除
                    onPressAndHold: function(mouse) {
                        // 检查是否点击了数据点
                        for (var i = 0; i < chartCanvas.dataPoints.length; i++) {
                            var point = chartCanvas.dataPoints[i];
                            var distance = Math.sqrt(Math.pow(mouse.x - point.x, 2) + Math.pow(mouse.y - point.y, 2));
                            
                            if (distance < 15) { // 点击容差
                                deleteDialog.recordIndex = point.index;
                                deleteDialog.recordDate = point.date;
                                deleteDialog.recordHeight = point.height;
                                deleteDialog.open();
                                return;
                            }
                        }
                    }
                }
            }
            
            // 统计信息（右下角，浮动在图表上方，可点击查看详情）
            Rectangle {
                id: statisticsBox
                anchors.right: parent.right
                anchors.bottom: parent.bottom
                anchors.margins: 20
                width: 180
                height: 85
                color: "#ecf0f1"
                radius: 10
                z: 10  // 确保在图表上方
                
                // 悬停效果
                border.color: statisticsMouseArea.containsMouse ? "#3498db" : "transparent"
                border.width: 2
                
                Behavior on border.color {
                    ColorAnimation { duration: 200 }
                }
                
                Behavior on scale {
                    NumberAnimation { duration: 150 }
                }
                
                Column {
                    anchors.fill: parent
                    anchors.margins: 10
                    spacing: 5
                    
                    Text {
                        text: "📊 统计信息"
                        font.pixelSize: 13
                        font.bold: true
                        color: "#2c3e50"
                    }
                    
                    Text {
                        text: "当前：" + heightRecordModel.currentHeight.toFixed(1) + " cm"
                        font.pixelSize: 11
                        color: "#34495e"
                    }
                    
                    Text {
                        text: "近一年：+" + heightRecordModel.lastYearGrowth.toFixed(1) + " cm"
                        font.pixelSize: 11
                        color: heightRecordModel.lastYearGrowth > 0 ? "#27ae60" : "#34495e"
                    }
                    
                    Text {
                        text: "点击查看详情 ›"
                        font.pixelSize: 10
                        color: "#95a5a6"
                        font.italic: true
                    }
                }
                
                MouseArea {
                    id: statisticsMouseArea
                    anchors.fill: parent
                    cursorShape: Qt.PointingHandCursor
                    hoverEnabled: true
                    onClicked: yearlyDetailsDialog.open()
                    onEntered: parent.scale = 1.05
                    onExited: parent.scale = 1.0
                }
            }
        }
        
        // 右上角添加按钮
        Rectangle {
            id: addButton
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.margins: 15
            width: 50
            height: 50
            color: "#3498db"
            radius: 25
            border.color: "white"
            border.width: 2
            z: 10  // 确保在最上层
            
            Text {
                anchors.centerIn: parent
                text: "+"
                font.pixelSize: 28
                font.bold: true
                color: "white"
            }
            
            MouseArea {
                anchors.fill: parent
                cursorShape: Qt.PointingHandCursor
                hoverEnabled: true
                onClicked: addRecordDialog.open()
                onEntered: parent.scale = 1.1
                onExited: parent.scale = 1.0
            }
            
            Behavior on scale {
                NumberAnimation { duration: 150 }
            }
        }
    }
    
    // 添加记录对话框（集成历史记录）
    Dialog {
        id: addRecordDialog
        title: "📏 身高记录管理"
        modal: true
        anchors.centerIn: parent
        width: 800
        height: 550
        
        Row {
            anchors.fill: parent
            spacing: 0
            
            // 左侧：历史记录列表
            Rectangle {
                width: parent.width * 0.5
                height: parent.height
                color: "#f8f9fa"
                border.color: "#e0e0e0"
                border.width: 1
                
                Column {
                    anchors.fill: parent
                    anchors.margins: 15
                    spacing: 10
                    
                    Text {
                        text: "📋 历史记录（共 " + heightRecordModel.count + " 条）"
                        font.pixelSize: 14
                        font.bold: true
                        color: "#2c3e50"
                    }
                    
                    ListView {
                        id: recordListView
                        width: parent.width
                        height: parent.height - 30
                        clip: true
                        model: heightRecordModel
                        spacing: 6
                        
                        delegate: Rectangle {
                            width: recordListView.width
                            height: 45
                            color: index % 2 === 0 ? "white" : "#ecf0f1"
                            radius: 5
                            border.color: "#dfe6e9"
                            border.width: 1
                            
                            Row {
                                anchors.fill: parent
                                anchors.margins: 10
                                spacing: 15
                                
                                Text {
                                    text: model.dateString
                                    font.pixelSize: 13
                                    color: "#34495e"
                                    width: parent.width * 0.5
                                    verticalAlignment: Text.AlignVCenter
                                }
                                
                                Text {
                                    text: model.height.toFixed(1) + " cm"
                                    font.pixelSize: 13
                                    font.bold: true
                                    color: "#3498db"
                                    verticalAlignment: Text.AlignVCenter
                                }
                            }
                        }
                    }
                }
            }
            
            // 右侧：添加记录表单
            Rectangle {
                width: parent.width * 0.5
                height: parent.height
                color: "white"
                
                Column {
                    anchors.fill: parent
                    anchors.margins: 20
                    spacing: 20
                    
                    Text {
                        text: "➕ 添加新记录"
                        font.pixelSize: 16
                        font.bold: true
                        color: "#2c3e50"
                    }
                    
                    // 日期输入
                    Column {
                        width: parent.width
                        spacing: 8
                        
                        Text {
                            text: "记录日期："
                            font.pixelSize: 14
                            color: "#34495e"
                        }
                        
                        Row {
                            spacing: 10
                            width: parent.width
                            
                            TextField {
                                id: dateInput
                                width: parent.width - 80
                                placeholderText: "yyyy-MM-dd"
                                text: Qt.formatDate(new Date(), "yyyy-MM-dd")
                                font.pixelSize: 14
                                
                                background: Rectangle {
                                    color: "#f8f9fa"
                                    border.color: dateInput.activeFocus ? "#3498db" : "#bdc3c7"
                                    border.width: 2
                                    radius: 5
                                }
                            }
                            
                            Button {
                                text: "今天"
                                width: 70
                                onClicked: {
                                    dateInput.text = Qt.formatDate(new Date(), "yyyy-MM-dd");
                                }
                            }
                        }
                    }
                    
                    // 身高输入
                    Column {
                        width: parent.width
                        spacing: 8
                        
                        Text {
                            text: "身高（厘米）："
                            font.pixelSize: 14
                            color: "#34495e"
                        }
                        
                        TextField {
                            id: heightInput
                            width: parent.width
                            placeholderText: "例如：115.5"
                            font.pixelSize: 14
                            validator: DoubleValidator {
                                bottom: 0
                                top: 300
                                decimals: 1
                            }
                            
                            background: Rectangle {
                                color: "#f8f9fa"
                                border.color: heightInput.activeFocus ? "#3498db" : "#bdc3c7"
                                border.width: 2
                                radius: 5
                            }
                        }
                    }
                    
                    // 说明文字
                    Text {
                        text: "💡 提示：相同日期会覆盖旧记录"
                        font.pixelSize: 11
                        color: "#7f8c8d"
                        wrapMode: Text.WordWrap
                        width: parent.width
                    }
                    
                    // 按钮
                    Row {
                        spacing: 15
                        anchors.horizontalCenter: parent.horizontalCenter
                        
                        Button {
                            text: "取消"
                            width: 100
                            onClicked: {
                                addRecordDialog.close()
                                heightInput.clear()
                                dateInput.text = Qt.formatDate(new Date(), "yyyy-MM-dd")
                            }
                        }
                        
                        Button {
                            text: "✅ 添加"
                            width: 100
                            enabled: heightInput.text.length > 0
                            
                            background: Rectangle {
                                color: parent.enabled ? (parent.pressed ? "#2980b9" : "#3498db") : "#95a5a6"
                                radius: 5
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: "white"
                                font: parent.font
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var height = parseFloat(heightInput.text);
                                if (isNaN(height) || height <= 0) {
                                    return;
                                }
                                
                                heightRecordModel.addRecord(dateInput.text, height);
                                heightInput.clear();
                                dateInput.text = Qt.formatDate(new Date(), "yyyy-MM-dd");
                                chartCanvas.requestPaint();
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    Dialog {
        id: deleteDialog
        title: "确认删除"
        modal: true
        anchors.centerIn: parent
        
        property int recordIndex: -1
        property string recordDate: ""
        property real recordHeight: 0.0
        
        width: 350
        height: 180
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "确定要删除这条记录吗？"
                font.pixelSize: 16
                color: "#2c3e50"
            }
            
            Rectangle {
                width: parent.width
                height: 60
                color: "#ecf0f1"
                radius: 5
                
                Column {
                    anchors.centerIn: parent
                    spacing: 5
                    
                    Text {
                        text: "📅 日期：" + deleteDialog.recordDate
                        font.pixelSize: 14
                        color: "#34495e"
                    }
                    
                    Text {
                        text: "📏 身高：" + deleteDialog.recordHeight.toFixed(1) + " cm"
                        font.pixelSize: 14
                        color: "#34495e"
                    }
                }
            }
            
            Row {
                spacing: 15
                anchors.horizontalCenter: parent.horizontalCenter
                
                Button {
                    text: "取消"
                    onClicked: deleteDialog.close()
                }
                
                Button {
                    text: "确认删除"
                    background: Rectangle {
                        color: parent.pressed ? "#c0392b" : "#e74c3c"
                        radius: 5
                    }
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    onClicked: {
                        heightRecordModel.deleteRecord(deleteDialog.recordIndex);
                        chartCanvas.requestPaint();
                        deleteDialog.close();
                    }
                }
            }
        }
    }
    
    // 往年详情对话框
    Dialog {
        id: yearlyDetailsDialog
        title: "📊 往年生长详情"
        modal: true
        anchors.centerIn: parent
        width: 450
        height: 400
        
        ScrollView {
            anchors.fill: parent
            
            Text {
                text: heightRecordModel.getYearlyGrowthDetails()
                font.pixelSize: 14
                color: "#2c3e50"
                wrapMode: Text.WordWrap
                width: yearlyDetailsDialog.width - 40
                lineHeight: 1.5
            }
        }
        
        footer: DialogButtonBox {
            Button {
                text: "关闭"
                DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole
            }
        }
    }
    
    // 数据变化时重绘
    Connections {
        target: heightRecordModel
        function onCountChanged() {
            chartCanvas.requestPaint();
        }
        function onCurrentHeightChanged() {
            chartCanvas.requestPaint();
        }
        function onLastYearGrowthChanged() {
            chartCanvas.requestPaint();
        }
        
        // 云同步信号处理
        function onCloudDataDifferent(cloudHash, localHash) {
            console.log("检测到云端身高记录数据不同");
            heightCloudSyncDialog.dialogType = "download";
            heightCloudSyncDialog.open();
        }
        
        function onLocalDataDifferent(localHash, cloudHash) {
            console.log("检测到本地身高记录数据不同");
            heightCloudSyncDialog.dialogType = "upload";
            heightCloudSyncDialog.open();
        }
        
        function onDataConsistent() {
            console.log("身高记录数据一致");
        }
        
        function onSyncStarted() {
            console.log("身高记录同步开始...");
        }
        
        function onSyncFinished() {
            console.log("身高记录同步完成！");
            chartCanvas.requestPaint();  // 同步完成后刷新图表
        }
        
        function onSyncFailed(error) {
            console.log("身高记录同步失败：" + error);
            heightSyncErrorDialog.errorMessage = error;
            heightSyncErrorDialog.open();
        }
    }
    
    // 云同步对话框
    Dialog {
        id: heightCloudSyncDialog
        property string dialogType: "download"  // "download" 或 "upload"
        
        title: dialogType === "download" ? "☁️ 发现云端数据" : "📤 本地数据已更新"
        modal: true
        anchors.centerIn: parent
        width: 450
        height: 250
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: heightCloudSyncDialog.dialogType === "download" 
                    ? "检测到云端身高记录与本地不同，是否从云端下载最新数据？\n\n⚠️ 下载将覆盖本地数据"
                    : "检测到本地身高记录已修改，是否上传到云端？\n\n💡 建议上传以保持数据同步"
                font.pixelSize: 14
                color: "#2c3e50"
                wrapMode: Text.WordWrap
                width: parent.width
            }
            
            Row {
                spacing: 15
                anchors.horizontalCenter: parent.horizontalCenter
                
                Button {
                    text: "取消"
                    width: 120
                    onClicked: {
                        heightCloudSyncDialog.close();
                    }
                }
                
                Button {
                    text: heightCloudSyncDialog.dialogType === "download" ? "⬇️ 从云端下载" : "☁️ 上传到云端"
                    width: 150
                    background: Rectangle {
                        color: parent.pressed ? "#2980b9" : "#3498db"
                        radius: 5
                    }
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font.bold: true
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    onClicked: {
                        heightCloudSyncDialog.close();
                        if (heightCloudSyncDialog.dialogType === "download") {
                            heightRecordModel.syncFromCloud();
                        } else {
                            heightRecordModel.syncToCloud();
                        }
                    }
                }
            }
        }
    }
    
    // 同步错误对话框
    Dialog {
        id: heightSyncErrorDialog
        property string errorMessage: ""
        
        title: "❌ 同步失败"
        modal: true
        anchors.centerIn: parent
        width: 400
        height: 200
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "身高记录同步失败：\n\n" + heightSyncErrorDialog.errorMessage
                font.pixelSize: 14
                color: "#e74c3c"
                wrapMode: Text.WordWrap
                width: parent.width
            }
            
            Button {
                text: "确定"
                width: 100
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: heightSyncErrorDialog.close()
            }
        }
    }
    
    // 组件加载完成后刷新图表
    Component.onCompleted: {
        chartCanvas.requestPaint();
    }
    
    // 组件销毁时（离开页面）检查是否需要同步
    Component.onDestruction: {
        console.log("HeightRecordView正在销毁，执行退出检查...");
        heightRecordModel.checkAndSyncOnExit();
    }
}

